//
// Created by 11510 on 2025/10/2.
//

#include "SetCommand.h"
#include "RegistryContainer.hpp"
#include "CameraApp.h"
xclib_client::SetCommand::SetCommand(CommandContext ctx) : ICommand("set", ctx) {};

std::optional<std::future<int>> xclib_client::SetCommand::run(const std::vector<std::string> &args, bool wait) {
    cxxopts::Options options("set", "set");
    options.add_options()
            ("u,unit", "unit", cxxopts::value<uint16_t>()->default_value(""))
            ("r,register", "register name", cxxopts::value<std::string>()->default_value(""))
            ("v,value", "value", cxxopts::value<std::string>()->default_value(""))
            ("help", "help");
    try {
        auto res = parseOptions(options, args);
        if (res.count("help")) {
            std::cout << options.help() << "\n";
            return std::nullopt;
        }
        auto u = res["unit"].as<uint16_t>();
        auto r = res["register"].as<std::string>();
        auto v = res["value"].as<std::string>();
        auto task = [u, r, v]() {
            std::stringstream ss(v);
            ss << std::hex << v;
            uint32_t value;
            ss >> value;
            if (ss.fail()) {
                std::cout <<  "Invalid value." << std::endl;
                return -1;
            }
            std::cout << "Set '" << r << "' on '" << u << "' to '" << v << "'...\n";

            registry::RegistryContainer::instance().get<CameraApp>("lazy")->set(u, r, value);
            return 0;
        };
        if (!wait) return make_optional(std::async(std::launch::async, task));
        else {
            task();
            return std::nullopt;
        }
    } catch (const cxxopts::exceptions::exception &e) {
        std::cerr << "set: " << e.what() << "\n";
        return std::nullopt;
    }
}

std::string xclib_client::SetCommand::shortHelp() const { return "set -u <unitmap> -r <register name> -v <valuea>"; }

std::string
xclib_client::SetCommand::longHelp() const { return "set -u <unitmap> -r <register name> -v <value>\n    set register value"; }